package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Usuario;
import dao.SqlServer;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class Login
 */
@WebServlet(name = "ServletLogin", urlPatterns = { "/ServletLogin" })
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private SqlServer dao = new SqlServer();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Capturar o Stream enviado pelo Android
				InputStreamReader inputStream = new InputStreamReader( request.getInputStream() ); 
				BufferedReader reader = new BufferedReader( inputStream );
				String entrada = reader.readLine();
				System.out.println(entrada);
				
				//Transformando a leitura da resposta para interpreta��o via JSON
				JSONObject jsonReq = JSONObject.fromObject( entrada  );
				//Capturando o valor enviado
				String usuario, senha;
				
				senha = jsonReq.getString("senha");
				usuario = jsonReq.getString("usuario");
				
				
				JSONObject jsonResp;
				
				boolean autenticado = false;
				
				if(dao.validarLogin(usuario, senha)){
					autenticado = true;
					Sessao sessao = Sessao.getSessao();
					sessao.addUsuario(new Usuario(usuario, dao.getPontos(usuario)));
				}				
				
				HashMap<String,String> dadosRetorno = new HashMap<String,String>();
				dadosRetorno.put( "message", autenticado+"" );
		        jsonResp = JSONObject.fromObject( dadosRetorno );
				response.setContentType("application/json");
				
				PrintWriter out = response.getWriter();
				out.print( jsonResp );
				out.flush();
	}

}
